/*
 * SignatureVerificationForm.java
 *
 * Created on __DATE__, __TIME__
 */

package clientPresentation;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import connection.exception.ConnectionResetException;

import messages.SignatureValidationRequestMessage;
import messages.SignatureValidationResponseMessage;

import client.ClientData;
import client.exceptions.SocketUninitializedException;

import utils.SignatureUtils;

/**
 *
 * @author  __USER__
 */
@SuppressWarnings("serial")
public class SignatureVerificationForm extends javax.swing.JFrame {

    /** Creates new form SignatureVerificationForm */
    public SignatureVerificationForm() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        fileField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        fileButton = new javax.swing.JButton();
        validationButton = new javax.swing.JButton();

        setDefaultCloseOperation(3);

        jLabel1.setText("Arquivo a Verificar:");

        fileButton.setText("Escolher Ficheiro");
        fileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileButtonActionPerformed(evt);
            }
        });

        validationButton.setText("Validar Assinatura");
        validationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                validationButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                        .addGroup(
                                layout.createParallelGroup(
                                        javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(
                                                layout.createSequentialGroup()
                                                .addContainerGap()
                                                .addGroup(
                                                        layout.createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                                .addGroup(
                                                                        layout.createSequentialGroup()
                                                                        .addComponent(
                                                                                fileField,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                                281,
                                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                                .addGap(18,
                                                                                        18,
                                                                                        18)
                                                                                        .addComponent(
                                                                                                fileButton))
                                                                                                .addComponent(
                                                                                                        jLabel1)))
                                                                                                        .addGroup(
                                                                                                                layout.createSequentialGroup()
                                                                                                                .addGap(155,
                                                                                                                        155,
                                                                                                                        155)
                                                                                                                        .addComponent(
                                                                                                                                validationButton)))
                                                                                                                                .addContainerGap(
                                                                                                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                                                                        Short.MAX_VALUE)));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(
                                layout.createParallelGroup(
                                        javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(fileButton)
                                        .addGroup(
                                                layout.createSequentialGroup()
                                                .addComponent(
                                                        jLabel1)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(
                                                                        fileField,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                        22,
                                                                        javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                                        .addGap(18, 18, 18)
                                                                        .addComponent(validationButton)
                                                                        .addContainerGap(
                                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                                Short.MAX_VALUE)));

        pack();
    }// </editor-fold>
    //GEN-END:initComponents

    private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // Abrir di�logo de 'Abrir Ficheiro'
        JFileChooser fc = new JFileChooser();
        int res = fc.showOpenDialog(this);

        // Se a opera��o falhou, abortar
        if (res != JFileChooser.APPROVE_OPTION)
            throw new RuntimeException(
            "Falha ao tentar abrir o ficheiro escolhido");

        // Coloca o nome do ficheiro dentro da caixa de texto
        fileField.setText(fc.getSelectedFile().getAbsolutePath());
    }

    private void validationButtonActionPerformed(java.awt.event.ActionEvent evt) {

        // Validação do ficheiro passado
        String filePath = fileField.getText();
        Boolean validated = SignatureUtils.isSignatureFile(filePath);
        if(!validated) {
            // Show Dialog
            JOptionPane.showMessageDialog(this, "O ficheiro escolhido não é válido.");

            return;
        }

        // Determinar se a assinatura tem verificação por VERICOP
        Boolean isVericop = SignatureUtils.isSignatureLocal(filePath);

        try {
            // Validar Assinatura
            Boolean result = false;
            String document = SignatureUtils.extractB64DocumentFromZip(filePath);
            String signatureStructure = SignatureUtils.extractSignatureStructFromZip(filePath);
            SignatureValidationRequestMessage req = 
                new SignatureValidationRequestMessage(document, signatureStructure);
            ClientData.getInstance().send(req);

            // Receber Resposta
            SignatureValidationResponseMessage res = (SignatureValidationResponseMessage) ClientData.getInstance().receive();
            result = res._result;

            // Mostrar Validade do Documento Assinado
            JOptionPane.showMessageDialog(this, "O documento é " + (result ? "válido" : "inválido")
                    + ", certificado pelo sistema " + (isVericop ? "VERICOP" : "CERTCOP"));
        } catch (ConnectionResetException e) {
        	JOptionPane.showMessageDialog(null, "A ligação com o servidor foi perdida. O sistema vai encerrar.");
        	System.exit(0);
        } catch (SocketUninitializedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SignatureVerificationForm().setVisible(true);
            }
        });
    }

    //GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JButton fileButton;

    private javax.swing.JTextField fileField;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JButton validationButton;
    // End of variables declaration//GEN-END:variables

}